package com.byyy.ccts.core.common.controller;

import com.byyy.ccts.core.model.AjaxJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 基础控制器 http://blog.csdn.net/catoop/article/details/51278675 写得不错的表单验证
 * 
 * @author 王存见
 * @date 2016-12-21
 * @version V 1.0
 */
public class BaseApiController {
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(value = {Exception.class})
	@ResponseBody
	public AjaxJson validationExceptionHandler(Exception e) {
		AjaxJson json = new AjaxJson();
		BindingResult result = null;
		if (e instanceof BindException) {
			result = ((BindException) e).getBindingResult();
		}
		else if (e instanceof MethodArgumentNotValidException) {
			result = ((MethodArgumentNotValidException) e).getBindingResult();
		}
		else {
			json.fail(e.getMessage());
			logger.error(e.getMessage(), e);
			return json;
		}
		String msg = null;
		if (result != null && result.hasErrors()) {
			msg = result.getAllErrors().get(0).getDefaultMessage();
			if (msg.contains("NumberFormatException")) {
				msg = "参数类型错误！";
			}
		}
		else {
			msg = "系统繁忙，请稍后再试...";
		}
		json.fail(msg);
		logger.error(msg, e);
		return json;
	}

}
